package org.sample.springbootredis.lock;

import java.util.Objects;

import org.redisson.api.RedissonClient;
import org.springframework.util.StringUtils;

public class RedissonLockConfig {

	private static final String REDIS_SEPARATOR = ":";

	private static final String TOKEN_LOCK_PREFIX = "LOCK";

	/**
	 * By default, a thread can hold a lock at most 30 seconds.
	 */
	private static final long DEFAULT_LEASE_MILLIS = 30000;

	/**
	 * By default, a thread blocks at most 30 seconds to try acquiring lock.
	 */
	private static final long DEFAULT_WAIT_MILLIS = 30000;

	RedissonClient redisson;

	String key;

	LockType type = LockType.LOCK;

	long leaseMillis = DEFAULT_LEASE_MILLIS;

	long waitMillis = DEFAULT_WAIT_MILLIS;

	public RedissonLockConfig(RedissonClient redisson, LockType type, LockKey baseKey) {
		Objects.requireNonNull(redisson);
		Objects.requireNonNull(type);
		Objects.requireNonNull(baseKey);
		this.redisson = redisson;
		this.type = type;
		this.key = TOKEN_LOCK_PREFIX + REDIS_SEPARATOR + baseKey.getValue();
	}

	/**
	 * Add lock sub key in Redis.
	 *
	 * @param subKey
	 * @return
	 */
	public void addLockSubKey(String subKey) {
		key = StringUtils.isEmpty(subKey) ? key : key + "_" + subKey;
	}

	public LockType getType() {
		return type;
	}

	public void setType(LockType type) {
		this.type = type;
	}

	public long getLeaseMillis() {
		return leaseMillis;
	}

	public void setLeaseMillis(long leaseMillis) {
		this.leaseMillis = leaseMillis;
	}

	public long getWaitMillis() {
		return waitMillis;
	}

	public void setWaitMillis(long waitMillis) {
		this.waitMillis = waitMillis;
	}

}
